package com.yjt.fresh.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import com.yjt.fresh.AuthResult;
import com.yjt.fresh.PayResult;
import com.yjt.fresh.R;
import com.yjt.fresh.adpater.AdpRvRechargeType;
import com.yjt.fresh.api.ApiGetRechargeType;
import com.yjt.fresh.api.ApiRechargeByAli;
import com.yjt.fresh.api.ApiRechargeByWeiXin;
import com.yjt.fresh.base.BaseSimpleActivity;
import com.yjt.fresh.bean.BeanRechargeType;
import com.yjt.fresh.bean.BeanWeiXinResult;
import com.yjt.fresh.constant.MyConstants;
import com.yjt.fresh.utils.CommonsToolsHelper;
import com.yjt.fresh.utils.PreferenceManager;
import com.yjt.fresh.widget.CustomToast;
import com.yjt.fresh.widget.GridSpacingItemDecoration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class AtyRechargeOnline extends BaseSimpleActivity {
    private static final int ALI_PAY = 1006;
    private static final int WEI_XIN_PAY = 1007;
    @BindView(R.id.back)
    RelativeLayout mBack;
    @BindView(R.id.rvAtyRechargeOnlineType)
    RecyclerView mRvType;

    @BindView(R.id.ivAtyRechargeOnlineWeiXinPay)
    ImageView mIvWeiXinPay;
    @BindView(R.id.llAtyRechargeOnlineWeiXinPay)
    LinearLayout mLlWeiXinPay;
    @BindView(R.id.ivAtyRechargeOnlineAli)
    ImageView mIvAli;
    @BindView(R.id.llAtyRechargeOnlineAliPay)
    LinearLayout mLlAliPay;
    @BindView(R.id.tvAtyRechargeOnlineArgument)
    TextView mTvArgument;
    @BindView(R.id.tvAtyRechargeOnlineToPay)
    TextView mTvToPay;
    private AdpRvRechargeType mAdpRechargeType;

    private int mPayWay = WEI_XIN_PAY;
    private String mRechargeID;
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private BeanWeiXinResult mWeiXinResult;
    private IWXAPI iwxapi;

    @Override
    protected int getContentView() {
        return R.layout.app_aty_recharge_online;
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
    }

    @Override
    protected void initEvent() {
        initRv();
        getData();
        initClick();
    }

    private void initClick() {
        mLlAliPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPayWay = ALI_PAY;
                mIvWeiXinPay.setImageResource(R.mipmap.a2_icon_02);
                mIvAli.setImageResource(R.mipmap.a2_icon_01);
            }
        });

        mLlWeiXinPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPayWay = WEI_XIN_PAY;
                mIvWeiXinPay.setImageResource(R.mipmap.a2_icon_01);
                mIvAli.setImageResource(R.mipmap.a2_icon_02);
            }
        });

        mTvToPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(mRechargeID)){
                    switch (mPayWay) {
                        case ALI_PAY:
                            aliPay();
                            break;
                        case WEI_XIN_PAY:
                            weiXinPay();
                            break;
                    }
                }else {
                    CustomToast.show("请先选择充值类型");
                }
            }
        });

        mTvArgument.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,AtyRechargeArgument.class);
                startActivity(intent);
            }
        });

        mAdpRechargeType.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mAdpRechargeType.setSelectPosition(position);
                mRechargeID = mAdpRechargeType.getItem(position).getRECHARGESETTING_ID();
            }
        });

        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void weiXinPay() {
        ApiRechargeByWeiXin apiRechargeByWeiXin = new ApiRechargeByWeiXin(new HttpOnNextListener<BeanWeiXinResult>() {

            @Override
            public void onNext(BeanWeiXinResult beanWeiXinResult) {
                mWeiXinResult = beanWeiXinResult;
                toWXPay();
            }

            @Override
            public void onReLogin() {

            }
        },mContext,true,false,false);

        Map<String,Object> map = new HashMap<>();
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        map.put("RECHARGESETTING_ID",mRechargeID);
        apiRechargeByWeiXin.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiRechargeByWeiXin);

    }
    @Override
    protected void onResume() {
        super.onResume();
        int wxPayResult = PreferenceManager.getInstance().getWXPayResult();
        if (wxPayResult != 110) {
            if (wxPayResult == 0) {
                //微信支付成功
                Toast.makeText(mContext, "支付成功", Toast.LENGTH_SHORT).show();
                finish();
            } else {
                //微信支付失败
                Toast.makeText(mContext, "支付未成功", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void toWXPay() {
        iwxapi = WXAPIFactory.createWXAPI(this, null); //初始化微信api
        iwxapi.registerApp(mWeiXinResult.getAppid()); //注册appid  appid可以在开发平台获取

        Runnable payRunnable = new Runnable() {  //这里注意要放在子线程
            @Override
            public void run() {
                PayReq request = new PayReq(); //调起微信APP的对象
                //下面是设置必要的参数，也就是前面说的参数,这几个参数从何而来请看上面说明
                request.appId = mWeiXinResult.getAppid();
                request.partnerId = mWeiXinResult.getPartnerid();
                request.prepayId = mWeiXinResult.getPrepayid();
                request.packageValue = "Sign=WXPay";
                request.nonceStr = mWeiXinResult.getNoncestr();
                request.timeStamp = mWeiXinResult.getTimestamp();
                request.sign = mWeiXinResult.getSign();
                iwxapi.sendReq(request);//发送调起微信的请求
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    private void aliPay() {

        ApiRechargeByAli apiRechargeByAli = new ApiRechargeByAli(new HttpOnNextListener<String>() {

            @Override
            public void onNext(String s) {
                payV2(s);
            }

            @Override
            public void onReLogin() {
                toLogin();
            }
        },mContext,true,false,false);
        Map<String,Object> map = new HashMap<>();
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        map.put("RECHARGESETTING_ID",mRechargeID);
        apiRechargeByAli.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiRechargeByAli);
    }

    /**
     * 支付宝支付业务
     */
    public void payV2(final String orderInfo) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(AtyRechargeOnline.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void getData() {
        ApiGetRechargeType apiGetRechargeType = new ApiGetRechargeType(new HttpOnNextListener<List<BeanRechargeType>>() {

            @Override
            public void onNext(List<BeanRechargeType> beanRechargeTypes) {
                mAdpRechargeType.setNewData(beanRechargeTypes);
            }

            @Override
            public void onReLogin() {
                toLogin();
            }
        },mContext,true,false,false);

        Map<String,Object> map = new HashMap<>();
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        apiGetRechargeType.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiGetRechargeType);
    }

    private void initRv() {
        GridLayoutManager layoutManager = new GridLayoutManager(mContext, 2);
        mRvType.setLayoutManager(layoutManager);
        mRvType.addItemDecoration(new GridSpacingItemDecoration(2, CommonsToolsHelper.dip2px(mContext, 8), true));
        List<BeanRechargeType> list = new ArrayList<>();
        mAdpRechargeType = new AdpRvRechargeType(R.layout.app_recycle_item_recharge_type,list);
        mRvType.setAdapter(mAdpRechargeType);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if ("9000".equals(resultStatus)) {
                        Toast.makeText(mContext, "支付成功", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        Toast.makeText(mContext, "支付未成功", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档

                    break;
                }
                default:
                    break;
            }
        }
    };
}
